package com.briup.corejava.day21;

import java.io.*;
import java.net.Socket;

/**
 * TCP协议下的客户端
 */
public class TcpClient {
    public static void main(String[] args) {
        // 准备ip地址和端口号
        String ip = "127.0.0.1";
        int port = 8888;
        // 创建一个socket，写入数据即可
        Socket socket = null;
        try {
            socket = new Socket(ip,port);
            // 使用输出流写入数据
            OutputStream outputStream = socket.getOutputStream();
            // 准备数据，简单一点字符串
            System.out.println("消息正在发送。。。");
            outputStream.write("hello,服务器在吗？".getBytes());

            // 发出去之后等待接收
            InputStream inputStream = socket.getInputStream();
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(inputStream)
            );
            String msg = br.readLine();
            System.out.println("服务器的回复："+msg);


        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
